package org.douxiaoban.client.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.URLSpan;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;
import org.douxiaoban.client.util.Panel;
import org.douxiaoban.client.R;

import org.douxiaoban.client.api.MiniBlogItemData;
import org.douxiaoban.client.api.MiniBlogItemData.ItemType;
import org.douxiaoban.client.api.MiniBlogList.SendType;
import org.douxiaoban.client.app.App;
import org.douxiaoban.client.app.Assistant;
import org.douxiaoban.client.util.ThreadTool;

import java.util.ArrayList;
import java.util.HashMap;


public class MiniBlogAdapter extends BaseAdapter{

	
	private ArrayList<MiniBlogItemData> m_listMiniBlog;
	private Context m_context;
	private HashMap <String, Bitmap> mHashMap;
	private ClickCallback mCallback;
	private ListView mListView;
	private AsyncImageLoader mAsyncImageLoader;
	
	private PopupWindow mPopupWindow;
	private View mPopupView;
	private View mParent;
	
	private final int IS_BIG_IMAGE = -100;

	private Handler m_handler = new Handler(){
		@Override
		public void handleMessage(Message msg){
			Bundle bundle = msg.getData();
			switch(msg.what){
				case Assistant.TOOLS_MSG_AVATAR:
					updateAvatar(bundle);
					break;
				case Assistant.TOOLS_MSG_IMAGE:
					updateImage(bundle);
					break;
				case Assistant.TOOLS_MSG_DEL:
					if(bundle.getBoolean(Assistant.TOOLS_KEY_DEL)){
						removeOne(bundle.getInt(Assistant.TOOLS_KEY_POSITION));
					}
					break;

					
				default:
					break;
			}
			super.handleMessage(msg);
		}
	};
	
	public MiniBlogAdapter(Context context){
		m_context = context;
		m_listMiniBlog = new ArrayList<MiniBlogItemData>();
		mHashMap = new HashMap<String, Bitmap>();
		//mListView = listView;
		mAsyncImageLoader = new AsyncImageLoader();
		//mCallback = (ClickCallback)context;
		
	}
	
	public void setListView(ListView listView){
		mListView = listView;
	}
	@Override
	public int getCount(){
		return m_listMiniBlog.size(); 
	}
	
	@Override
	public Object getItem(int index){
		if(index < 0 || index > m_listMiniBlog.size()){
			return null;
		}
		return m_listMiniBlog.get(index);
	}
	
	public long getItemId(int index){
		return 0;
	}
	public View getView(int position, View view, ViewGroup vGroup){
		if ( position > m_listMiniBlog.size()){
			return view;
		} 
		LayoutInflater layoutInflater = LayoutInflater.from(m_context);
		view = layoutInflater.inflate(R.layout.miniblog_item, null);
		mCallback = (ClickCallback)m_context;
		TextView tvName = (TextView)view.findViewById(R.id.miniBlogUserName);
		TextView tvContent = (TextView)view.findViewById(R.id.miniBlogContent);
		TextView tvTime = (TextView)view.findViewById(R.id.miniBlogTime);
		//TextView tvType = (TextView)view.findViewById(R.id.miniBlogType);
		ImageView ivAvatar = (ImageView)view.findViewById(R.id.miniBlogAvatar);
		ImageView ivImage = (ImageView)view.findViewById(R.id.miniBlogImage);
		
		final MiniBlogItemData itemData = m_listMiniBlog.get(position);
		
		view.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v){
				mCallback.itemClick(itemData);
			}
		});
		
		view.setOnLongClickListener(new OnLongClickListener(){

			@Override
			public boolean onLongClick(View arg0) {
				mCallback.itemClick(itemData);
				return true;
			}
			
		});
		
		ivAvatar.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v){
				((ClickCallback)m_context).avatarClick(itemData.m_sName, itemData.m_sUserId);
			}
		});
		
		//是我说或者推荐时,显示回应
		if( MiniBlogItemData.ItemType.SAYING == itemData.m_itemType
			|| MiniBlogItemData.ItemType.RECOMMENDATION == itemData.m_itemType){
			TextView btnRev = (TextView)view.findViewById(R.id.miniBlogRev);
			btnRev.setVisibility(View.VISIBLE);
			btnRev.setOnClickListener(new OnClickListener(){
				@Override
				public void onClick(View v){
					//是我说则弹web view
					String id = String.valueOf(itemData.m_iId);
					if(MiniBlogItemData.ItemType.SAYING == itemData.m_itemType){
						mCallback.revBtnClick("回应"+itemData.m_sName, SendType.REV_SAYING, id);
					}else{
					//是推荐....
						id = itemData.m_sRecommendId;
						mCallback.revBtnClick("回应"+itemData.m_sName, SendType.REV_RECOMMEND, id);
					}					
				}
			});
		}
		
		//自己的广播 显示删除按钮 38533562 							 
//		if(itemData.m_sUserId.equals(App.userId)){
//			TextView textDel = (TextView)view.findViewById(R.id.miniBlogDel);
//			//textDel.setVisibility(View.VISIBLE);
//			final int pos = position;
//			textDel.setOnClickListener(new OnClickListener(){
//				@Override
//				public void onClick(View v){
//					String id = String.valueOf(itemData.m_iId);
//					ThreadTool.instace(m_context).delMiniBlog(id, pos, m_handler);
//				}
//			});
//		}
		tvName.setText(itemData.m_sName);
//		tvContent.setText(itemData.m_sContent);
//		Spanned spanned = Html.fromHtml(itemData.m_sHtmlContetn);
		tvContent.setText(itemData.m_sContent);
//		tvContent.setOnLongClickListener(new OnLongClickListener(){
//			@Override
//			public boolean onLongClick(View v){
//				mCallback.itemClick(itemData);
//				return true;
//			}
//		});
	
		
//		tvContent.setMovementMethod(LinkMovementMethod.getInstance());
//		CharSequence text = tvContent.getText();
//		if(text instanceof Spannable){
//			  Spannable text = Spannable.Factory.getInstance().newSpannable(itemData.m_sHtmlContetn);
//
//			   int end = text.length();  
////	            Spannable sp = (Spannable)tv.getText();  
//	            URLSpan[] urls=text.getSpans(0, end, URLSpan.class);   
//	            SpannableStringBuilder style=new SpannableStringBuilder(text);  
//	            style.clearSpans();//should clear old spans  
//	            for(URLSpan url : urls){  
//	            	MyURLSpan myURLSpan = new MyURLSpan(url.getURL());  
//	                style.setSpan(myURLSpan,text.getSpanStart(url),text.getSpanEnd(url),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);  
//	            }  
//	            tvContent.setText(style); 
	            
//		}
		
	
		
//        CharSequence text =summaryView.getText();
//
//        if(text instanceof Spannable){
//            //在评论尾端加入支持点击事件的文本
//            Spannable sp = (Spannable)summaryView.getText();
//            URLSpan[] urls = sp.getSpans(0, text.length(), URLSpan.class);
//            SpannableStringBuilder style = new SpannableStringBuilder(text);
//            style.clearSpans();
//
//            for(URLSpan s:urls){
//                MyURLSpan myURLSpan =new MyURLSpan(rr.reviewId,rr,(_subjectReviewAvatarImageView.size()-1));
//                style.setSpan(myURLSpan,sp.getSpanStart(s),sp.getSpanEnd(s),
//                        Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
//            }
//            summaryView.setText(style);
//        }
		
	
		tvTime.setText(itemData.m_sTime);
	//	tvType.setText(itemData.m_sType);
		
		ivAvatar.setTag(itemData.m_sAvatarLink);
		//用户头像	
        Drawable cacheImage = mAsyncImageLoader.loadDrawable(itemData.m_sAvatarLink,new AsyncImageLoader.ImageCallback(){
            @Override
            public void imageLoaded(Drawable imageDrawable, String imageUrl) {
                ImageView imageViewByTag = (ImageView)mListView.findViewWithTag(itemData.m_sAvatarLink);
                if(imageViewByTag !=null)
                    imageViewByTag.setImageDrawable(imageDrawable);
            }
        });

        if(cacheImage ==null){
        	//ivAvatar.setImageResource(R.drawable.default_book_icon_small);
        }else{
        	ivAvatar.setImageDrawable(cacheImage);
        }
//		if(!mHashMap.containsKey(itemData.m_sUserId)){
//			mHashMap.put(itemData.m_sUserId, null);
//			ThreadTool.instace(m_context).
//			getAvatar(itemData.m_sUserId, itemData.m_sAvatarLink, m_handler, position);
//		}else{
//			ivAvatar.setImageBitmap(mHashMap.get(itemData.m_sUserId));
//		}
			
		//带图片的miniBlog
		if(null == itemData.m_bmImage){
			if(null != itemData.m_sImageLink){
				ThreadTool.instace(m_context).
					getImage(itemData.m_sImageLink, m_handler, position);
			}else{
				ivImage.setVisibility(View.GONE);
			}
		}else{
			ivImage.setImageBitmap(itemData.m_bmImage);
			ivImage.setOnClickListener(new OnClickListener(){
				@Override
				public void onClick(View v){
					//点击查看大图 
					//大图规则 icon，替换成photo； spic替换成lpic（
					if(itemData.m_sImageLink.contains("icon")){
						itemData.mLImageLink = itemData.m_sImageLink.replace("icon", "photo");
						showBigPix(itemData.mLImageLink);
					}else if(itemData.m_sImageLink.contains("spic")){
						itemData.mLImageLink = itemData.m_sImageLink.replace("spic", "lpic");
						showBigPix(itemData.mLImageLink);
					}
					
				}
			});
		}
		return view;
	}
	
	private	class MyURLSpan extends ClickableSpan{  
		  
        private String mUrl;  
        MyURLSpan(String url) {  
            mUrl =url;  
        }  
          
        @Override  
        public void onClick(View widget) {  
          //do what you want with the mUrl  
        	Uri uri=Uri.parse(mUrl);
        	Intent intent=new Intent(Intent.ACTION_VIEW,uri);
        	m_context.startActivity(intent);

        }  
 }  
	
	public void delItem(int id){
		int pos = -1;
//		String sId;
		for(int i=0; i < m_listMiniBlog.size(); i++){
			MiniBlogItemData data = m_listMiniBlog.get(i);
			if(id == data.m_iId){
				pos = i;
				break;
			}
		}
		if(-1 != pos){
			ThreadTool.instace(m_context).delMiniBlog(String.valueOf(id), pos, m_handler);
		}
		
	}
	
	//获取新的数据,往后加....
	public void addDataTail(ArrayList<MiniBlogItemData> list){
		m_listMiniBlog.addAll(list);
		this.notifyDataSetChanged();
	}
	
	//获取数据往指定的index 插入,
	public void addDataPre(ArrayList<MiniBlogItemData> list){
		m_listMiniBlog.addAll(0,list);
		this.notifyDataSetChanged();
	}
	
	//获取第一的id值 
	public int getFirstId(){
		if(!m_listMiniBlog.isEmpty()){
			MiniBlogItemData data = m_listMiniBlog.get(0);
			return data.m_iId;	
		}
		return -1;
	}
	
	//获取最后一个的id值
	public int getLastId(){
		MiniBlogItemData data = m_listMiniBlog.get(m_listMiniBlog.size()-1);
		return data.m_iId;
	}
	
	public ItemType getItemType(int pos){
		return m_listMiniBlog.get(pos).m_itemType;
	}
	
	private void updateAvatar(Bundle bundle){
		ThreadTool.ImageSerialz serialz;
		serialz = (ThreadTool.ImageSerialz)bundle.getSerializable(Assistant.TOOLS_KEY_AVATAR);
		
		MiniBlogItemData item = m_listMiniBlog.get(serialz.m_iPosition);
		mHashMap.put(item.m_sUserId, serialz.m_bitmap);
		item.m_bmAvatar = serialz.m_bitmap;
		this.notifyDataSetChanged();
	}
	
	private void updateImage(Bundle bundle){
		ThreadTool.ImageSerialz serialz;
		serialz = (ThreadTool.ImageSerialz)bundle.getSerializable(Assistant.TOOLS_KEY_IMAGE);
		
		if(IS_BIG_IMAGE != serialz.m_iPosition){
			MiniBlogItemData item = m_listMiniBlog.get(serialz.m_iPosition);
			item.m_bmImage = serialz.m_bitmap;
			this.notifyDataSetChanged();
		}else{
			updateBigImage(serialz.m_bitmap);
		}

	}
	
	public void clear(){
		m_listMiniBlog.clear();
		notifyDataSetChanged();
	}
	
	/**
	 * 删除指定
	 * @param index
	 */
//	public void removeItem(int index){
//		m_listMiniBlog.remove(index);
//	}
	
	public interface ClickCallback{
		//回应按钮, type  0 我说, 1 回应我说, 2 回应推荐
		void revBtnClick(String title, SendType type, String str);
		void avatarClick(String userName, String userId);
		void itemClick(MiniBlogItemData data);
	}
	/**
	 * 打开panel
	 * 
	 * @param title title的内容! 
	 */
	private void openPanel(String title){
		Panel panel = (Panel)((Activity) m_context).findViewById(R.id.topPanel);
		EditText edit = (EditText)((Activity) m_context).findViewById(R.id.panelEdit);
	//	TextView tv = (TextView)((Activity)m_context).findViewById(R.id.panelTitle);
	//	tv.setText(title);
		panel.setOpen(false, true);	
		edit.clearComposingText();
	}
	
	/**
	 * 删除一条miniBlog //ui上删除
	 * @param pos 被删除的miniBlog 的位置
	 */
	private void removeOne(int pos){
		m_listMiniBlog.remove(pos);
		this.notifyDataSetChanged();
	}
	
	private void showBigPix(String url){
		LayoutInflater inflater = LayoutInflater.from(m_context);
		mPopupView = inflater.inflate(R.layout.show_big_image, null);
	
		mPopupWindow = new PopupWindow(mPopupView, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, true);
		mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
		mPopupWindow.showAtLocation(mParent, Gravity.TOP | Gravity.LEFT, 0, 0);
		ThreadTool.instace(m_context).getImage(url, m_handler, IS_BIG_IMAGE);
	}
	
	private void updateBigImage(Bitmap bitmap){
		ImageView imageView= (ImageView)mPopupView.findViewById(R.id.bigImage);
		imageView.setVisibility(View.VISIBLE);
		
		ProgressBar progressBar = (ProgressBar)mPopupView.findViewById(R.id.bigImageProgressBar);
		progressBar.setVisibility(View.GONE);
		imageView.setImageBitmap(bitmap);
		
		//使得点击图无效过
		imageView.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v){
				
			}
		});
		
		//点击图周围使得popupWindow 消失
		View view = mPopupView.findViewById(R.id.bigImageLayout);
		view.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v){
				mPopupWindow.dismiss();
			}
		});
	}
	//初始化后必须设置 parent view
	public void setParentView(View v){
		mParent = v;
	}
//	public int getIndex(MiniBlogItemData data){
//		for()
//	}
}

		